<template>
  <div class="xtx-numbox">
    <div class="label" v-if="isShowLabel">数量</div>
    <div class="numbox">
      <a href="javascript:;" @click="decrease">-</a>
      <input type="text" readonly :value="curNum" />
      <a href="javascript:;" @click="add">+</a>
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxNumbox',
  // 子传父
  emits: ['update:modelValue'],
  // 控制最大最小数量
  props: {
    // 父传子控制是否显示文字'数量'
    isShowLabel: {
      type: Boolean,
      default: true,
    },
    // 双向绑定变量接收
    modelValue: {
      type: Number,
      default: 1,
    },
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
  },
  setup(props, { emit }) {
    const curNum = ref(1)
    // 加按钮处理函数
    function add() {
      if (curNum.value === props.max) return
      curNum.value++
      // 同步数据curNum到modelValue
      emit('update:modelValue', curNum.value)
    }
    // 减按钮处理函数
    function decrease() {
      if (curNum.value === props.min) return
      curNum.value--
      emit('update:modelValue', curNum.value)
    }

    // 监听购买数量变化
    watch(
      () => props.modelValue,
      (newval) => {
        // 同步数据modelValue到curNum
        curNum.value = newval
      },
      { immediate: true }
    )

    return { add, decrease, curNum }
  },
}
</script>
<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
